package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleMapper roleMapper;

    private final RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<Role> findPage(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Role role = BeanUtil.toBean(roleDto, Role.class);
        List<Role> list = roleMapper.findPage(role);
        Page<Role> page = (Page<Role>) list;
        return PageResponse.of(page,Role.class);
    }

    @Override
    public Boolean insertRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        int count = roleMapper.insertSelective(role);
        return count > 0;
    }

    @Override
    public Boolean updateRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        int count = roleMapper.updateByPrimaryKeySelective(role);
        roleResourceMapper.deleteByPrimaryKey(role.getId());
        String[] checkedResourceNos = roleDto.getCheckedResourceNos();
        for (String checkedResourceNo : checkedResourceNos) {
            RoleResource roleResource = RoleResource.builder().roleId(role.getId()).resourceNo(checkedResourceNo).build();
            roleResourceMapper.insertSelective(roleResource);
        }
        return count > 0;
    }

    @Override
    public Set<String> getResourcesById(Long roleId) {
        Set<String> set = roleResourceMapper.selectByRoleId(roleId);
        return set;
    }

    @Override
    public void deleteByRoleId(Long roleId) {
        roleMapper.deleteByRoleId(roleId);
        roleResourceMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public List<RoleVo> initRoles() {
        List<RoleVo> list = roleMapper.initRoles();
        return list;
    }
}
